﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.HtmlControls;

namespace SCCN.Utility
{
    public class IOHelper
    {

        #region 目录管理

        /// <summary>
        /// 创建指定位置的新目录
        /// </summary>
        /// <param name="Path">要创建目录的所在路径</param>
        public static bool CreateFolder(string folderPath)
        {
            try
            {
                Directory.CreateDirectory(folderPath);
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw ex;
            }
        }

        /// <summary>
        /// 删除指定目录
        /// </summary>
        /// <param name="folderPath">目录所在路径</param>
        /// <returns></returns>
        public static bool DeleteFolder(string folderPath)
        {
            try
            {
                Directory.Delete(folderPath, true); //删除已空文件夹                
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw ex;
            }

        }

       

        /// <summary>
        /// 获取文件夹大小
        /// </summary>
        /// <param name="dirPath">文件夹路径</param>
        /// <returns></returns>
        public static long GetDirectoryLength(string dirPath)
        {
            if (!Directory.Exists(dirPath))
            {
                return 0;
            }
            long len = 0;
            DirectoryInfo di = new DirectoryInfo(dirPath);
            foreach (FileInfo fi in di.GetFiles())
            {
                len += fi.Length;
            }
            DirectoryInfo[] dis = di.GetDirectories();
            if (dis.Length > 0)
            {
                for (int i = 0; i < dis.Length; i++)
                {
                    len += GetDirectoryLength(dis[i].FullName);
                }
            }
            return len;
        }


        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="filePath"></param>
        public static void FileOpera_DeleteDirectory(string directoryPath)
        {
            string path = HttpContext.Current.Server.MapPath(directoryPath);

            if (Directory.Exists(path))
            {
                try
                {
                    Directory.Delete(path, true);
                }
                catch (IOException ee)
                {
                    HttpContext.Current.Response.Write("<script>alert(" + ee.Message + ")</script>");
                }
            }
        }
        #endregion


        #region 文件管理

        /// <summary>
        /// 创建指定文件
        /// </summary>
        /// <param name="Path">指定路径</param>
        public static void FileCreate(string Path)
        {
            FileInfo CreateFile = new FileInfo(Path); //创建文件
            if (!CreateFile.Exists)
            {
                using (FileStream FS = CreateFile.Create())
                {
                    FS.Close();
                }
            }
        }

        /// <summary>
        ///删除指定文件
        /// </summary>
        /// <param name="path"></param>
        public static void DetletFile(string filePath)
        {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
        }

        /// <summary>
        ///批量删除指定的文件名
        /// </summary>
        /// <param name="filePath">指定的文件夹</param>
        /// <param name="fileName">要删除的文件名称</param>
        public static void DeleteFile(string filePath, IList<string> fileNames)
        {
            if (Directory.Exists(filePath))
            {
                foreach (string d in Directory.GetFiles(filePath))
                {

                    foreach (string fileName in fileNames)
                    {

                        FileInfo f = new FileInfo(d);

                        if (File.Exists(d) && f.Name == fileName)
                        {
                            File.Delete(d);
                            break;
                        }
                    }
                }

            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath">相对路径</param>
        public static void FileOpera_DeleteFile(string filePath)
        {
            string path = HttpContext.Current.Server.MapPath(filePath);

            if (File.Exists(path))
            {
                try
                {
                    File.Delete(path);
                }
                catch (IOException ee)
                {
                    HttpContext.Current.Response.Write("<script>alert(" + ee.Message + ")</script>");
                }
            }
        }


        #endregion


        #region 文件读写

        #endregion


        /// <summary>
        /// asp.net上传图片并生成缩略图
        /// </summary>
        /// <param name="upImage">HtmlInputFile控件</param>
        /// <param name="sSavePath">保存的路径,些为相对服务器路径的下的文件夹</param>
        /// <param name="sThumbExtension">缩略图的thumb</param>
        /// <param name="intThumbWidth">生成缩略图的宽度</param>
        /// <param name="intThumbHeight">生成缩略图的高度</param>
        /// <returns>缩略图名称</returns>
        public static string UpLoadImage(HtmlInputFile upImage, string sSavePath, string sThumbExtension, int intThumbWidth, int intThumbHeight)
        {
            string sThumbFile = "";
            string sFilename = "";

            if (upImage.PostedFile != null)
            {
                HttpPostedFile myFile = upImage.PostedFile;
                int nFileLen = myFile.ContentLength;
                if (nFileLen == 0)
                {
                    return "没有选择上传图片";
                }

                //获取upImage选择文件的扩展名
                string extendName = System.IO.Path.GetExtension(myFile.FileName).ToLower();
                //判断是否为图片格式
                if (extendName != ".jpg" && extendName != ".jpge" && extendName != ".gif" && extendName != ".bmp" && extendName != ".png")
                {
                    return "图片格式不正确";
                }
                byte[] myData = new Byte[nFileLen];
                myFile.InputStream.Read(myData, 0, nFileLen);
                sFilename = System.IO.Path.GetFileName(myFile.FileName);
                int file_append = 0;
                //检查当前文件夹下是否有同名图片,有则在文件名+1
                while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename)))
                {
                    file_append++;
                    sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                        + file_append.ToString() + extendName;
                }
                System.IO.FileStream newFile
                    = new System.IO.FileStream(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename),
                    System.IO.FileMode.Create, System.IO.FileAccess.Write);
                newFile.Write(myData, 0, myData.Length);
                newFile.Close();
                //以上为上传原图
                try
                {
                    //原图加载
                    using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename)))
                    {
                        //原图宽度和高度
                        int width = sourceImage.Width;
                        int height = sourceImage.Height;
                        int smallWidth;
                        int smallHeight;

                        //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽  和 原图的高/缩略图的高)
                        if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight)
                        {
                            smallWidth = intThumbWidth;
                            smallHeight = intThumbWidth * height / width;
                        }
                        else
                        {
                            smallWidth = intThumbHeight * width / height;
                            smallHeight = intThumbHeight;
                        }

                        //判断缩略图在当前文件夹下是否同名称文件存在
                        file_append = 0;
                        sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + extendName;

                        while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sThumbFile)))
                        {
                            file_append++;
                            sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + extendName;
                        }
                        //缩略图保存的绝对路径
                        string smallImagePath = System.Web.HttpContext.Current.Server.MapPath(sSavePath) + sThumbFile;

                        //新建一个图板,以最小等比例压缩大小绘制原图
                        using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight))
                        {
                            //绘制中间图
                            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                            {
                                //高清,平滑
                                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                g.Clear(Color.Black);
                                g.DrawImage(
                                sourceImage,
                                new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),
                                new System.Drawing.Rectangle(0, 0, width, height),
                                System.Drawing.GraphicsUnit.Pixel
                                );
                            }
                            //新建一个图板,以缩略图大小绘制中间图
                            using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight))
                            {
                                //绘制缩略图
                                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1))
                                {
                                    //高清,平滑
                                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                    g.Clear(Color.Black);
                                    int lwidth = (smallWidth - intThumbWidth) / 2;
                                    int bheight = (smallHeight - intThumbHeight) / 2;
                                    g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel);
                                    g.Dispose();
                                    bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                                }
                            }
                        }
                    }
                }
                catch
                {
                    //出错则删除
                    System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename));
                    return "图片格式不正确";
                }
                //返回缩略图名称
                return sThumbFile;
            }
            return "没有选择图片";
        }







        /// <summary>
        /// 图片缩略
        /// </summary>
        /// <param name="hpf">上传图片类</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <param name="path">图片存放路径(包含图片名)-相对路径</param>
        public static void ReductionImg(HttpPostedFile hpf, int width, int height, string path)
        {
            byte[] bytes = new byte[hpf.ContentLength];
            Stream stream = hpf.InputStream;
            System.Drawing.Image img = System.Drawing.Image.FromStream(stream);

            int ywidth = img.Width;
            int yheight = img.Height;
            if (ywidth >= yheight)
            {
                height = (int)Math.Floor(Convert.ToDouble(yheight) * (Convert.ToDouble(width) / Convert.ToDouble(ywidth)));
            }
            else
            {
                width = (int)Math.Floor(Convert.ToDouble(ywidth) * (Convert.ToDouble(height) / Convert.ToDouble(yheight)));
            }

            Bitmap b = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(b);
            g.InterpolationMode = InterpolationMode.High;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.Clear(Color.Transparent);
            g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(0, 0, ywidth, yheight), GraphicsUnit.Pixel);

            string filePath = HttpContext.Current.Server.MapPath(path);
            try
            {
                g.DrawString("水印文字", new Font("Courier New", 14), new SolidBrush(Color.Red), 60, 60);
                img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("<script>alert('" + ex.Message.ToString() + "');</script>");
            }
            finally
            {
                //释放资源
                img.Dispose();
                g.Dispose();
                b.Dispose();
            }
        }
    }
}
